package com.itheima.controller.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@WebServlet("/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map resultMap = new HashMap();
        try {
            String index1 = request.getParameter("index");
            Part part = request.getPart("file");
            String name = part.getSubmittedFileName();
            int index = name.lastIndexOf(".");
            String substring = name.substring(index);
            InputStream inputStream = part.getInputStream();
            String realPath = request.getServletContext().getRealPath("upload");
            String s = UUID.randomUUID().toString();
            String fileName = s.replaceAll("-", "");
            FileOutputStream fos = new FileOutputStream(realPath+"/"+fileName+substring);
            IOUtils.copy(inputStream,fos);
            resultMap.put("flag",true);
            resultMap.put("fileName",fileName+substring);
            resultMap.put("index",index1);
        } catch (Exception e) {
            resultMap.put("flag",false);
            e.printStackTrace();
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(resultMap);
        response.getWriter().write(s);
    }
}
